package com.zmn.mcc.admin.controller.staff.dingtalk;

import com.taobao.api.ApiException;
import com.zmn.common.dto.LoginStaff;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.request.RequestUtil;
import com.zmn.mcc.admin.controller.MccBaseController;
import com.zmn.mcc.business.interfaces.staff.StaffBService;
import com.zmn.mcc.business.interfaces.staff.dingtalk.DingTalkService;
import com.zmn.mcc.business.interfaces.staff.ip.StaffIpInfoBService;
import com.zmn.mcc.cache.StaffCache;
import com.zmn.mcc.common.constant.StaffChangeLogConsts;
import com.zmn.mcc.common.constant.StaffConsts;
import com.zmn.mcc.model.entity.log.IpInfo;
import com.zmn.mcc.model.entity.staff.McStaff;
import com.zmn.mcc.model.entity.staff.dingtalk.StaffDingTalk;
import com.zmn.mcc.model.entity.staff.staffchangelog.StaffChangeLog;
import com.zmn.mcc.model.entity.staff.staffleaveoffice.StaffLeaveOffice;
import com.zmn.mcc.services.interfaces.staff.StaffService;
import com.zmn.mcc.services.interfaces.staff.staffchangelog.StaffChangeLogService;
import com.zmn.mcc.services.interfaces.staff.staffleaveoffice.StaffLeaveOfficeService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@RestController
@RequestMapping("/staff/dingtalk/")
public class DingTalkController extends MccBaseController {
    private Logger logger = LoggerFactory.getLogger(DingTalkController.class);

    @Resource
    DingTalkService dingTalkService;

    @Resource
    StaffService staffService;

    @Resource
    private StaffCache staffCache;

    @Resource
    StaffBService staffBService;

    @Resource
    StaffLeaveOfficeService staffLeaveOfficeService;

    @Resource
    StaffChangeLogService staffChangeLogService;

    @Resource
    StaffIpInfoBService staffIpInfoBService;

    /**
     * 同步钉钉
     *
     * @param staffId
     * @return
     */
    @RequestMapping(value = "synchro")
    @ResponseBody
//    @RequiresPermissions("staff/dingtalk/synchro")
    public ResponseDTO synchro(@RequestParam(value = "staffId", defaultValue = "0") Integer staffId,
                               @RequestParam(value = "dTalkId", defaultValue = "0") String dTalkId,
                               HttpServletRequest request) {

        if (NumberUtil.isNullOrZero(staffId)) {
            return ResponseDTO.fail(121701, "员工ID不能为空！");
        }

        // 更新员工钉钉号码
        if (Objects.nonNull(dTalkId) && dTalkId.length() != 0 && !Objects.equals("0", dTalkId)) {
            int count = staffService.countByDTalkIdAndNotStaffId(staffId, dTalkId);
            if (count > 0) {
                return ResponseDTO.fail(121703, "钉钉userId已存在");
            }

            staffService.updateDtalkIdByStaffId(staffId, dTalkId, getStaffName());
        }

        McStaff staff = staffService.findByKey(staffId);
        if (Objects.isNull(staff.getDTalkId()) || staff.getDTalkId().length() == 0 || Objects.equals("0", staff.getDTalkId())) {
            return ResponseDTO.fail(121702, "没有员工钉钉userId");
        }

        try {
            StaffDingTalk staffDingTalk = dingTalkService.getDingTalkResultByuserId(staff.getDTalkId());
            staffBService.synchroStaffByStaffDingTalkAndStaff(staff, staffDingTalk);
        } catch (ApiException e) {
            return ResponseDTO.fail("更新失败，请稍后再试");
        }

        // 添加员工同步钉钉日志
        StaffChangeLog staffChangeLog = new StaffChangeLog();
        staffChangeLog.setStaffId(staff.getStaffId());
        staffChangeLog.setBeforContent("-");
        staffChangeLog.setAfterContent("操作同步钉钉，钉钉userID：" + staff.getDTalkId());
        LoginStaff staffLogin = getLoginStaff();
        staffChangeLog.setAbutmenterId(staffLogin.getStaffId());
        staffChangeLog.setAbutmenter(staffLogin.getRealName());
        staffChangeLog.setAbutmenterDeptId(staffLogin.getDeptId() + "");
        staffChangeLog.setAbutmenterDeptName(staffLogin.getDeptName());
        staffChangeLog.setChangeType(StaffChangeLogConsts.CHANGE_TYPE_DING_TALK);
        staffChangeLog.setCreateTime(DateUtil.getNow());
        String ip = RequestUtil.getRequestIp(request);
        IpInfo ipInfo = staffIpInfoBService.locationByIP(ip);
        if (Objects.nonNull(ipInfo)) {
            staffChangeLog.setAbutmenterCity(ipInfo.getProvince() + "-" + ipInfo.getCity());
        }
        staffChangeLog.setIp(ip);
        staffChangeLogService.insert(staffChangeLog);

        return ResponseDTO.success(null, "操作成功！");
    }

    /**
     * 描述:将用户设置为IP白名单页面
     *
     * @param staffId 员工的id
     * @return boolean
     * @author wangjie
     * @since 9:31 2019/5/31
     **/
    @RequestMapping(value = "toSetDingTalkId")
    @ResponseBody
    public ModelAndView toSetDingTalkId(@RequestParam(value = "staffId", defaultValue = "0") Integer staffId) {
        ModelAndView modelAndView = new ModelAndView("staff/setDingTalkUserId");
        McStaff staff = staffId > 0 ? staffService.findByKey(staffId) : new McStaff();
        modelAndView.addObject("staff", staff);
        return modelAndView;
    }

    /**
     * 描述:操作离职
     *
     * @param staffId 员工的id
     * @return boolean
     * @author tanghongjun
     * @since 9:31 2020/6/3
     **/
    @RequestMapping(value = "leave")
    @ResponseBody
    public ResponseDTO leave(@RequestParam(value = "staffId", defaultValue = "0") Integer staffId) {

        if (NumberUtil.isNullOrZero(staffId)) {
            return ResponseDTO.fail(121701, "员工ID不能为空！");
        }
        McStaff staff = staffId > 0 ? staffService.findByKey(staffId) : new McStaff();
        if (Objects.isNull(staff)) {
            return ResponseDTO.fail(121704, "员工不存在！");
        }

        StaffLeaveOffice staffLeaveOffice = staffLeaveOfficeService.findByStaffId(staffId);
        if (Objects.nonNull(staffLeaveOffice)) {
            return ResponseDTO.success("跳转到离职页面");
        }

        // 员工钉钉ID不存在，直接离职
        if (StringUtils.isEmpty(staff.getDTalkId()) || Objects.equals("0", staff.getDTalkId())) {
            this.leaveStaff(staff);
            return ResponseDTO.success("跳转到离职页面");
        }

        return ResponseDTO.fail(121706, "系统异常，请稍后再试！");
    }

    private void leaveStaff(McStaff staff) {
        // 禁用员工账号，将员工设置为离职
        // 离职只修改员工状态  账号状态不禁用 20200720
        staff.setStaffStatus(StaffConsts.STAFF_STATUS_LEAVE);
        staff.setUpdater(getStaffName());
        staff.setUpdateTime(DateUtil.getNow());

        staffService.updateByKey(staff);

        // 添加员工离职日志
        LoginStaff staffLogin = getLoginStaff();
        StaffChangeLog staffChangeLog = StaffChangeLog.builder().staffId(staff.getStaffId()).beforContent("-").afterContent("状态从正常修改为离职")
                .abutmenterId(staffLogin.getStaffId()).abutmenter(staffLogin.getRealName()).abutmenterDeptId(staffLogin.getDeptId() + "")
                .abutmenterDeptName(staffLogin.getDeptName()).changeType(StaffChangeLogConsts.CHANGE_TYPE_LEAVE).createTime(DateUtil.getNow()).build();
        staffChangeLogService.insert(staffChangeLog);
    }
}
